import net.sshiffon.*

class LocalFileViewerController {
    // these will be injected by Griffon
    def model
    def view

    def SEPARATOR= java.io.File.separator

    void mvcGroupInit(Map<String,Object> args) {
        model.refresh()
    }

    boolean start()
	{
    	return true
	}

    String getAbsoluteDirFromRelative(dir)
    {
        return model.currentFolder + SEPARATOR + dir
    }
    
    void cd(dir)
    {
        model.currentFolder = dir
        refresh()
    }


    void mkdir(entry)
    {
    	if(entry)
    	{
    		mkdir(entry.name)
    	} else {
    		logger.warn('nothing to mkdir')
    	}
    }
    
    void mkdir(String entryName)
    {
        view.doOutside {
            try {
                new File(model.currentFolder  + SEPARATOR + entryName).mkdir()
                doLater {
                    refresh()
                }
            } catch (e)
            {
                logger.error("Error making folder ${name}",e)
            }
        }
    }
    void processEntry(entry)
    {
        def type = entry.type
        def file = entry.name
        if(type=='D')
        {
            if('..'.equals(file))
            {
            	upDir()
            } else {
                model.currentFolder+= SEPARATOR + file
                refresh()
            }
        } else {
            model.parentController.model.remoteGroup.controller.upload(model.currentFolder + SEPARATOR + file)
        }
    }

    def upDir = { evt = null ->
        if(model.currentFolder.lastIndexOf(SEPARATOR)>-1)
        {
            def newFolder = model.currentFolder.substring(0,model.currentFolder.lastIndexOf(SEPARATOR))
            logger.debug("cding up to $newFolder")
            model.currentFolder= newFolder
            refresh()
        } else {
        	logger.warn("nowhere up to go (!)")
        }
    }

    void refresh()
    {
        model.refresh()
        view.loadFolder(model.currentFolder , model.folderContents)
    }

    void delete(int modelRef)
    {
    	def entry= model.folderContents[modelRef]
        logger.info("deleting ${entry}")
        new File( model.currentFolder + SEPARATOR + entry.name).delete()
        logger.info("deleted ${entry}")
    }
    void upload(int modelRef)
    {
        def entry= model.folderContents[modelRef]
        model.parentController.model.remoteGroup.controller.upload(model.currentFolder + SEPARATOR + entry.name)
        
    }
    void quit()
    {
		view.fileList.metaClass.removeProppertyChangeListener= { 
    			String n, c ->
    			logger.debug('covering Groovy1.6 bug')
    			view.fileList.removePropertyChangeListener(n, c)
    		}
		destroyMVCGroup(model.mvcId);

    }

}